<template>
  <div class="settings-container">
    <div class="settings-header">
      <h1>系统设置</h1>
    </div>
    
    <!-- 设置内容 -->
    <div class="settings-content">
      <!-- 基本设置 -->
      <div class="settings-section">
        <div class="section-title">基本设置</div>
        <div class="section-content">
          <Form v-model:model="basicSettings" :rules="basicRules" ref="basicFormRef">
            <FormItem label="用户名" field="username">
              <Input 
                v-model:value="basicSettings.username" 
                placeholder="请输入用户名"
                :maxlength="20"
                show-word-limit
              />
            </FormItem>
            
            <FormItem label="货币符号" field="currencySymbol">
              <Select v-model:value="basicSettings.currencySymbol" placeholder="选择货币符号">
                <SelectOption value="¥">人民币 (¥)</SelectOption>
                <SelectOption value="$">美元 ($)</SelectOption>
                <SelectOption value="€">欧元 (€)</SelectOption>
                <SelectOption value="£">英镑 (£)</SelectOption>
              </Select>
            </FormItem>
            
            <FormItem label="语言" field="language">
              <Select v-model:value="basicSettings.language" placeholder="选择语言">
                <SelectOption value="zh-CN">简体中文</SelectOption>
                <SelectOption value="en-US">English</SelectOption>
              </Select>
            </FormItem>
            
            <FormItem label="主题" field="theme">
              <RadioGroup v-model:value="basicSettings.theme">
                <Radio value="light">浅色主题</Radio>
                <Radio value="dark">深色主题</Radio>
                <Radio value="auto">跟随系统</Radio>
              </RadioGroup>
            </FormItem>
          </Form>
        </div>
      </div>
      
      <!-- 数据设置 -->
      <div class="settings-section">
        <div class="section-title">数据管理</div>
        <div class="section-content">
          <div class="data-management">
            <Button 
              type="primary" 
              @click="exportData"
              class="data-button"
              icon="icon-download"
            >
              导出数据
            </Button>
            
            <Button 
              type="default" 
              @click="showImportModal = true"
              class="data-button"
              icon="icon-upload"
            >
              导入数据
            </Button>
            
            <Button 
              type="default" 
              danger
              @click="showResetModal = true"
              class="data-button"
              icon="icon-delete"
            >
              重置数据
            </Button>
          </div>
          
          <div class="data-info">
            <p>数据存储在浏览器本地存储中，导出数据可备份您的财务记录。</p>
            <p class="warning-text">注意：重置数据将删除所有交易记录和设置，此操作不可恢复。</p>
          </div>
        </div>
      </div>
      
      <!-- 提醒设置 -->
      <div class="settings-section">
        <div class="section-title">提醒设置</div>
        <div class="section-content">
          <Form v-model:model="notificationSettings" ref="notificationFormRef">
            <FormItem label="月度报表提醒" field="monthlyReport">
              <Switch v-model:checked="notificationSettings.monthlyReport" />
              <span class="switch-label">每月第一天发送月度财务报表</span>
            </FormItem>
            
            <FormItem label="支出预警" field="expenseAlert">
              <div class="alert-setting">
                <Switch v-model:checked="notificationSettings.expenseAlert" />
                <span class="switch-label">当月支出超过预算时提醒</span>
              </div>
              <div v-if="notificationSettings.expenseAlert" class="alert-threshold">
                <InputNumber 
                  v-model:value="notificationSettings.alertThreshold"
                  :min="10" 
                  :max="100" 
                  :step="5"
                  style="width: 100px"
                />
                <span class="threshold-label">预算百分比 (%)</span>
              </div>
            </FormItem>
          </Form>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="settings-actions">
        <Button @click="resetSettings">重置</Button>
        <Button type="primary" @click="saveSettings">保存设置</Button>
      </div>
    </div>
    
    <!-- 导入数据模态框 -->
    <Modal 
      v-model:visible="showImportModal" 
      title="导入数据" 
      @ok="handleImportData"
      @cancel="handleCancelImport"
    >
      <div class="modal-content">
        <p>请选择要导入的数据文件（JSON格式）：</p>
        <input 
          ref="fileInputRef"
          type="file" 
          accept=".json"
          style="display: none"
          @change="handleFileChange"
        />
        <Button 
          type="default" 
          @click="$refs.fileInputRef.click()"
          class="file-upload-button"
        >
          选择文件
        </Button>
        <div v-if="selectedFile" class="selected-file">
          <span>{{ selectedFile.name }}</span>
          <Button 
            type="text" 
            danger
            size="small"
            @click="clearSelectedFile"
          >
            移除
          </Button>
        </div>
        <p class="import-hint">导入数据将覆盖当前所有数据，请谨慎操作！</p>
      </div>
    </Modal>
    
    <!-- 重置数据确认模态框 -->
    <Modal 
      v-model:visible="showResetModal" 
      title="确认重置"
      @ok="handleResetData"
      @cancel="handleCancelReset"
      okText="确认重置"
      cancelText="取消"
      okType="danger"
    >
      <div class="modal-content">
        <p class="warning-text">警告：此操作将删除所有交易记录和设置，且无法恢复！</p>
        <p>请确认是否要继续重置所有数据？</p>
        <Input 
          v-model:value="resetConfirmText" 
          placeholder="请输入'reset'以确认"
          class="confirm-input"
        />
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useFinanceStore } from '../store/finance';
import { 
  Form, 
  FormItem, 
  Input, 
  Select, 
  RadioGroup, 
  Radio, 
  Switch, 
  Button, 
  Modal, 
  InputNumber 
} from '@arco-design/web-vue';
import { IconDownload, IconUpload, IconDelete } from '@arco-design/web-vue/es/icon';

const financeStore = useFinanceStore();

// 状态管理
const showImportModal = ref(false);
const showResetModal = ref(false);
const selectedFile = ref<File | null>(null);
const resetConfirmText = ref('');
const fileInputRef = ref<HTMLInputElement>();
const basicFormRef = ref<Form>();
const notificationFormRef = ref<Form>();

// 表单数据
const basicSettings = ref({
  username: '',
  currencySymbol: '¥',
  language: 'zh-CN',
  theme: 'light'
});

const notificationSettings = ref({
  monthlyReport: true,
  expenseAlert: false,
  alertThreshold: 80
});

// 表单验证规则
const basicRules = {
  username: [{
    required: true,
    message: '请输入用户名',
    trigger: 'blur'
  }, {
    min: 2,
    max: 20,
    message: '用户名长度应在2-20个字符之间',
    trigger: 'blur'
  }],
  currencySymbol: [{
    required: true,
    message: '请选择货币符号',
    trigger: 'change'
  }],
  language: [{
    required: true,
    message: '请选择语言',
    trigger: 'change'
  }],
  theme: [{
    required: true,
    message: '请选择主题',
    trigger: 'change'
  }]
};

// 方法：保存设置
const saveSettings = async () => {
  if (basicFormRef.value) {
    const valid = await basicFormRef.value.validate();
    if (valid) {
      // 保存基本设置
      localStorage.setItem('basicSettings', JSON.stringify(basicSettings.value));
      
      // 保存通知设置
      localStorage.setItem('notificationSettings', JSON.stringify(notificationSettings.value));
      
      // 应用主题
      applyTheme(basicSettings.value.theme);
      
      Modal.success({
        title: '成功',
        content: '设置已保存！',
        onOk: () => {}
      });
    }
  }
};

// 方法：重置设置
const resetSettings = () => {
  Modal.confirm({
    title: '确认重置',
    content: '确定要重置所有设置吗？',
    onOk: () => {
      loadDefaultSettings();
    }
  });
};

// 方法：导出数据
const exportData = () => {
  const financeData = localStorage.getItem('financeData');
  const basicSettings = localStorage.getItem('basicSettings');
  const notificationSettings = localStorage.getItem('notificationSettings');
  
  const exportData = {
    financeData: financeData ? JSON.parse(financeData) : {},
    basicSettings: basicSettings ? JSON.parse(basicSettings) : {},
    notificationSettings: notificationSettings ? JSON.parse(notificationSettings) : {},
    exportDate: new Date().toISOString()
  };
  
  const dataStr = JSON.stringify(exportData, null, 2);
  const dataBlob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(dataBlob);
  
  const link = document.createElement('a');
  link.href = url;
  link.download = `sana-finance-backup-${new Date().toISOString().split('T')[0]}.json`;
  link.click();
  
  URL.revokeObjectURL(url);
};

// 方法：处理文件选择
const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    selectedFile.value = target.files[0];
  }
};

// 方法：清除选择的文件
const clearSelectedFile = () => {
  selectedFile.value = null;
  if (fileInputRef.value) {
    fileInputRef.value.value = '';
  }
};

// 方法：处理导入数据
const handleImportData = () => {
  if (!selectedFile.value) {
    Modal.warning({
      title: '提示',
      content: '请先选择要导入的文件',
      onOk: () => {}
    });
    return;
  }
  
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const data = JSON.parse(e.target?.result as string);
      
      if (data.financeData) {
        localStorage.setItem('financeData', JSON.stringify(data.financeData));
      }
      
      if (data.basicSettings) {
        localStorage.setItem('basicSettings', JSON.stringify(data.basicSettings));
        basicSettings.value = { ...data.basicSettings };
        applyTheme(basicSettings.value.theme);
      }
      
      if (data.notificationSettings) {
        localStorage.setItem('notificationSettings', JSON.stringify(data.notificationSettings));
        notificationSettings.value = { ...data.notificationSettings };
      }
      
      Modal.success({
        title: '成功',
        content: '数据导入成功！请刷新页面以应用新数据。',
        onOk: () => {
          location.reload();
        }
      });
    } catch (error) {
      Modal.error({
        title: '错误',
        content: '文件格式错误，无法导入数据',
        onOk: () => {}
      });
    }
  };
  
  reader.readAsText(selectedFile.value);
};

// 方法：处理重置数据
const handleResetData = () => {
  if (resetConfirmText.value.toLowerCase() !== 'reset') {
    Modal.warning({
      title: '提示',
      content: '请输入正确的确认文本',
      onOk: () => {}
    });
    return;
  }
  
  Modal.confirm({
    title: '最终确认',
    content: '这是最后确认！所有数据将被永久删除，无法恢复。确定要继续吗？',
    okType: 'danger',
    onOk: () => {
      // 清除所有数据
      localStorage.removeItem('financeData');
      localStorage.removeItem('basicSettings');
      localStorage.removeItem('notificationSettings');
      
      // 重新加载默认设置
      loadDefaultSettings();
      
      Modal.success({
        title: '成功',
        content: '数据已重置！请刷新页面以应用更改。',
        onOk: () => {
          location.reload();
        }
      });
    }
  });
};

// 方法：取消导入
const handleCancelImport = () => {
  clearSelectedFile();
};

// 方法：取消重置
const handleCancelReset = () => {
  resetConfirmText.value = '';
};

// 方法：应用主题
const applyTheme = (theme: string) => {
  if (theme === 'dark') {
    document.body.setAttribute('arco-theme', 'dark');
  } else if (theme === 'light') {
    document.body.removeAttribute('arco-theme');
  } else if (theme === 'auto') {
    const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    if (isDarkMode) {
      document.body.setAttribute('arco-theme', 'dark');
    } else {
      document.body.removeAttribute('arco-theme');
    }
  }
};

// 方法：加载默认设置
const loadDefaultSettings = () => {
  basicSettings.value = {
    username: '用户',
    currencySymbol: '¥',
    language: 'zh-CN',
    theme: 'light'
  };
  
  notificationSettings.value = {
    monthlyReport: true,
    expenseAlert: false,
    alertThreshold: 80
  };
};

// 方法：从本地存储加载设置
const loadSettingsFromStorage = () => {
  // 加载基本设置
  const basicSettingsStr = localStorage.getItem('basicSettings');
  if (basicSettingsStr) {
    basicSettings.value = { ...JSON.parse(basicSettingsStr) };
  }
  
  // 加载通知设置
  const notificationSettingsStr = localStorage.getItem('notificationSettings');
  if (notificationSettingsStr) {
    notificationSettings.value = { ...JSON.parse(notificationSettingsStr) };
  }
  
  // 应用主题
  applyTheme(basicSettings.value.theme);
};

// 组件挂载时加载设置
onMounted(() => {
  loadSettingsFromStorage();
});
</script>

<style scoped>
.settings-container {
  padding: 24px;
}

.settings-header {
  margin-bottom: 24px;
}

.settings-header h1 {
  font-size: 24px;
  margin: 0;
}

.settings-content {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 24px;
}

.settings-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--color-border);
}

.section-content {
  padding-left: 8px;
}

.data-management {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.data-button {
  flex: 1;
  min-width: 150px;
}

.data-info {
  color: var(--color-text-secondary);
  font-size: 14px;
  line-height: 1.6;
}

.warning-text {
  color: var(--color-warning);
}

.switch-label {
  margin-left: 8px;
  color: var(--color-text-secondary);
}

.alert-setting {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.alert-threshold {
  display: flex;
  align-items: center;
  padding-left: 32px;
  margin-top: 8px;
}

.threshold-label {
  margin-left: 8px;
  color: var(--color-text-secondary);
}

.settings-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 32px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border);
}

.modal-content {
  padding: 16px 0;
}

.modal-content p {
  margin: 0 0 16px 0;
  line-height: 1.6;
}

.file-upload-button {
  margin-bottom: 16px;
}

.selected-file {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: var(--color-bg-1);
  border: 1px solid var(--color-border);
  border-radius: 4px;
  margin-bottom: 16px;
}

.import-hint {
  color: var(--color-text-secondary);
  font-size: 14px;
}

.confirm-input {
  margin-top: 16px;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-content {
    padding: 16px;
  }
  
  .data-management {
    flex-direction: column;
  }
  
  .data-button {
    width: 100%;
  }
  
  .settings-actions {
    flex-direction: column;
  }
  
  .settings-actions Button {
    width: 100%;
  }
  
  .alert-threshold {
    padding-left: 0;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>